#include "Window.h"
#include "Application.h"
#include <assert.h>

Window* Window::gMainWindow = NULL;

LRESULT CALLBACK GlobalWndProc(
	HWND hWnd,
	UINT uMsg,
	WPARAM wParam,
	LPARAM lParam )
{
	assert( Window::getMainWindow() );

	return Window::getMainWindow()->WndProc( hWnd, uMsg, wParam, lParam );
}

Window::Window(unsigned left, unsigned top, unsigned width, unsigned height, const char* name )
:mLeft(left),
mTop(top),
mWidth(width),
mHeight(height),
mName(name)
{
	mbActive = false;
	gMainWindow = this;
}

Window::~Window()
{
	DestroyWindow(mhWnd);
	gMainWindow = NULL;
}

void Window::RegisterWindowClass(WNDCLASSEX* pWc)
{
	WNDCLASSEX wcex;

	if(pWc)
	{
		wcex = *pWc;
	}
	else
	{
		wcex.cbSize = sizeof(WNDCLASSEX); 

		wcex.style			= CS_HREDRAW | CS_VREDRAW;
		wcex.lpfnWndProc	= (WNDPROC)GlobalWndProc;
		wcex.cbClsExtra		= 0;
		wcex.cbWndExtra		= 0;
		wcex.hInstance		= Application::gethInstance();
		wcex.hIcon			= NULL;
		wcex.hCursor		= LoadCursor(NULL, IDC_ARROW);
		wcex.hbrBackground	= (HBRUSH)(COLOR_WINDOW+1);
		wcex.lpszMenuName	= NULL;
		wcex.lpszClassName	= mName.c_str();
		wcex.hIconSm		= NULL;
	}
	
	RegisterClassEx(&wcex);
}

void Window::InitInstance()
{
	mhWnd = CreateWindow(mName.c_str(), mName.c_str(), WS_OVERLAPPEDWINDOW,
		mLeft, mTop, mWidth, mHeight, NULL, NULL, Application::gethInstance(), NULL);

	ShowWindow(mhWnd, SW_SHOW);
	UpdateWindow(mhWnd);
}

LRESULT Window::WndProc(
	HWND hWnd,
	UINT uMsg,
	WPARAM wParam,
	LPARAM lParam )
{
	switch( uMsg ) 
	{
	case WM_CREATE:
		{
			getMainWindow()->mhWnd = hWnd;
			getMainWindow()->mbActive = true;
			break;
		}
	case WM_KEYDOWN:
		{
			switch( wParam )
			{
			case VK_ESCAPE:
				{
					PostQuitMessage(0);
					break;
				}
			default:
				{
					break;
				}
			}
		}
	case WM_DESTROY:
		{
			PostQuitMessage(0);
			break;
		}
	default:
		return DefWindowProc(hWnd, uMsg, wParam, lParam);
	}

	return 0;
}